﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace CoffeePotServer
{
    /// <summary>
    /// File: Server_Response.cs
    /// Author: James Dibble 10009689
    /// Last Revision: 17/03/12
    /// SVN Address:
    /// http://code.google.com/p/cnos-coffeepot-server/source/browse/branches/DibbleBranch/CoffeePotServerLib/CoffeePotServerLib/Server_Response.cs
    /// </summary>
    public class Server_Response
    {
        #region Attributes
        private NetworkStream _clientStream;
        #endregion

        #region Constructor
        /// <summary>
        /// Create an object to send messages to a client.
        /// </summary>
        /// <param name="thisNetStream">A network stream to the client.</param>
        public Server_Response(NetworkStream thisNetStream)
        {
            _clientStream = thisNetStream;
        }
        #endregion

        #region Methods
        /// <summary>
        /// Send a message to the client.  All messages are prefixed 'HTCPCP/1.0'.
        /// </summary>
        /// <param name="strMessage">The message to send</param>
        public void SendLine(String strMessage)
        {
            strMessage = "HTCPCP/1.0 " + strMessage + "\r\n";
            _clientStream.Write(ConvertStringToByteArray(strMessage), 0, strMessage.Length);
        }

        /// <summary>
        /// Send a message to the client.
        /// </summary>
        /// <param name="strMessage">The message to send in plain format</param>
        public void SendLine(byte[] byteArrMessage)
        {
            //Use LINQ's Concat method to add the HTCPCP/1.0 parts to the header.
            byte[] final = (byte[])ConvertStringToByteArray("HTCPCP/1.0 ").Concat(byteArrMessage).Concat(ConvertStringToByteArray("\r\n"));
            _clientStream.Write(final, 0, final.Length);
        }

        //From my Generic library.
        /// <summary>
        /// Create a byte array from a given string.
        /// </summary>
        /// <param name="strToConvert">The string to convert</param>
        /// <returns>A byte array representation of the given string</returns>
        private byte[] ConvertStringToByteArray(String strToConvert)
        {
            byte[] byteBuff = new byte[strToConvert.Length];
            char[] charBuff = strToConvert.ToCharArray();
            for (int intCount = 0; intCount < charBuff.Length; intCount++)
            {
                byteBuff[intCount] = Convert.ToByte(charBuff[intCount]);
            }
            return byteBuff;
        }
        #endregion
    }
}